package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.redp.bizimpl.upmp.dao.UpmpRoleMapper;
import cc.rengu.redp.bizimpl.upmp.domain.*;
import cc.rengu.redp.bizimpl.upmp.dao.UpmpPrivilegeCheckMapper;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpPrivilegeCheckService;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpPrivilegeCheckVO;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.domain.RedpConstant;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.DateUtil;
import cc.rengu.redp.common.utils.SortUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author System
 */
@Service("UpmpPrivilegeCheckService")
@DS("upmp")
public class UpmpPrivilegeCheckServiceImpl extends ServiceImpl<UpmpPrivilegeCheckMapper, UpmpPrivilegeCheck> implements IUpmpPrivilegeCheckService {

    @Autowired
    private UpmpRoleMapper upmpRoleMapper;
    @Override
    public IPage<UpmpPrivilegeCheckVO> findPageList(UpmpPrivilegeCheckVO privilegeCheckVO, QueryRequest queryRequest) {

        try {
            Page<UpmpPrivilegeCheckVO> page = new Page<>();
            SortUtil.handlePageSort(queryRequest, page, "", "", true);
            IPage<UpmpPrivilegeCheckVO> retPage =  this.baseMapper.findPageList(page,privilegeCheckVO);
            List<UpmpPrivilegeCheckVO> records = retPage.getRecords();
            /*records.forEach(upmpPrivilegeCheckVO->{
                List<UpmpPrivilegeCheckVO> roles = this.baseMapper.findRoleList(upmpPrivilegeCheckVO);
                List<String> roleIds = roles.stream().map(it ->String.valueOf(it.getRoleId())).collect(Collectors.toList());
                List<String> roleNames = roles.stream().map(it ->String.valueOf(it.getRoleName())).collect(Collectors.toList());
                upmpPrivilegeCheckVO.setRoleId(String.join(StringPool.COMMA, roleIds));
                upmpPrivilegeCheckVO.setRoleName(String.join(StringPool.COMMA, roleNames));
            });*/

            for(int i=0;i<records.size();i++){
                UpmpPrivilegeCheckVO upmpPrivilegeCheckVO = records.get(i);
                List<UpmpPrivilegeCheckVO> roles = this.baseMapper.findRoleList(upmpPrivilegeCheckVO);
                List<String> roleIds = roles.stream().map(it ->String.valueOf(it.getRoleId())).collect(Collectors.toList());
                List<String> roleNames = roles.stream().map(it ->String.valueOf(it.getRoleName())).collect(Collectors.toList());
                upmpPrivilegeCheckVO.setRoleId(String.join(StringPool.COMMA, roleIds));
                upmpPrivilegeCheckVO.setRoleName(String.join(StringPool.COMMA, roleNames));
                upmpPrivilegeCheckVO.setId(String.valueOf((retPage.getCurrent()-1)*retPage.getSize()+i));
            }

            return retPage;
        } catch (Exception e) {
            log.error("获取权限审核配置列表失败", e);
            return null;
        }
    }

    @Override
    public List<UpmpPrivilegeCheck> findList(UpmpPrivilegeCheck privilegeCheck) {
        LambdaQueryWrapper<UpmpPrivilegeCheck> queryWrapper = new LambdaQueryWrapper<>();
        findCondition(queryWrapper, privilegeCheck);
        queryWrapper.orderByAsc(UpmpPrivilegeCheck::getCreateTime);
        return this.baseMapper.selectList(queryWrapper);
    }

    @Override
    public void add(UpmpPrivilegeCheckVO privilegeCheck)throws RedpException {
        List<UpmpPrivilegeCheck> list = Lists.newArrayList();
        String[] roleIds = privilegeCheck.getRoleId().split(StringPool.COMMA);
        for(String roleId:roleIds){
            UpmpPrivilegeCheck data = new UpmpPrivilegeCheck();
            BeanUtils.copyProperties(privilegeCheck,data);
            data.setRoleId(roleId);
            data.setCreateTime(DateUtil.getDateFormat(new Date(),DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN));
            data.setCrtOrgId("");
            data.setOprId("");
            data.setId(null);
            list.add(data);
        }
        this.saveBatch(list);
    }

    @Override
    public void update(UpmpPrivilegeCheckVO privilegeCheck) throws RedpException {
        UpmpPrivilegeCheck condition = new UpmpPrivilegeCheck();
        condition.setInstId(privilegeCheck.getInstId());
        condition.setPerms(privilegeCheck.getPerms());
        condition.setChannelType(privilegeCheck.getChannelType());
        List<UpmpPrivilegeCheck> dbDatas = this.findList(condition);
        String[] roleIds = privilegeCheck.getRoleId().split(StringPool.COMMA);

        List<String> delList = Lists.newArrayList();
        List<UpmpPrivilegeCheck> addList = Lists.newArrayList();
        List<UpmpPrivilegeCheck> updList = Lists.newArrayList();
        for(UpmpPrivilegeCheck db:dbDatas){
            boolean exist=false;
            for(String roleId:roleIds){
                if(roleId.equals(db.getRoleId())){
                    exist=true;
                }
            }
            if(exist){//数据库和提交的数据都存在时做修改
                db.setChecked(privilegeCheck.getChecked());
                db.setCheckLevel(privilegeCheck.getCheckLevel());
                db.setLastOprId("");
                db.setLastUpdateTime(DateUtil.getDateFormat(new Date(),DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN));
                updList.add(db);
            }else{//数据库存在、提交数据不存在时做删除
                delList.add(db.getId());
            }
        }

        for(String roleId:roleIds){
            boolean exist=false;
            for(UpmpPrivilegeCheck db:dbDatas){
                if(roleId.equals(db.getRoleId())){
                    exist=true;
                }
            }
            if(!exist) {//提交数据存在，数据库不存在时做新增
                UpmpPrivilegeCheck newData = new UpmpPrivilegeCheck();
                BeanUtils.copyProperties(privilegeCheck,newData);
                newData.setId(null);
                newData.setRoleId(roleId);
                newData.setCreateTime(DateUtil.getDateFormat(new Date(),DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN));
                newData.setCrtOrgId("");
                newData.setOprId("");
                addList.add(newData);
            }
        }
        if(addList.size()>0){
            this.saveBatch(addList);
        }
        if(updList.size()>0) {
            this.saveOrUpdateBatch(updList);
        }
        if(delList.size()>0) {
            this.removeByIds(delList);
        }
    }

    @Override
    public void delete(String[] ids) throws Exception {
        this.removeByIds(Arrays.asList(ids));
    }

    @Override
    public Map<String, Object> getPrivilegeCheckRoles(UpmpPrivilegeCheckVO privilegeCheck)throws RedpException {

        Map<String, Object> result = new HashMap<>();
        try {
            LambdaQueryWrapper<UpmpRole> queryWrapper1 = new LambdaQueryWrapper<>();
            if (StringUtils.isNotBlank(privilegeCheck.getInstId())) {
                queryWrapper1.eq(UpmpRole::getInstId, privilegeCheck.getInstId());
            }else {
                log.error("查询法人行角色请求参数[instId]异常");
                throw new RedpException("查询法人行角色请求参数异常");
            }
            List<UpmpRole> roles = upmpRoleMapper.selectList(queryWrapper1);


            List<String> privilegeCheckIds = Lists.newArrayList();
            LambdaQueryWrapper<UpmpPrivilegeCheck> queryWrapper2 = new LambdaQueryWrapper<>();
            if (StringUtils.isNotBlank(privilegeCheck.getInstId())) {
                queryWrapper2.eq(UpmpPrivilegeCheck::getInstId, privilegeCheck.getInstId());
            }else {
                log.error("查询法人行权限审核配置请求参数[instId]未传入");
                throw new RedpException("查询法人行权限审核配置请求参数[instId]未传入");
            }
            if (StringUtils.isNotBlank(privilegeCheck.getChannelType())) {
                queryWrapper2.eq(UpmpPrivilegeCheck::getChannelType, privilegeCheck.getChannelType());
            }else {
                log.error("查询法人行权限审核配置请求参数[channelType]未传入");
                throw new RedpException("查询法人行权限审核配置请求参数[channelType]未传入");
            }
            if (!ObjectUtils.isEmpty(privilegeCheck.getCheckLevel())) {
                queryWrapper2.eq(UpmpPrivilegeCheck::getCheckLevel, privilegeCheck.getCheckLevel());
            }else {
                log.error("查询法人行权限审核配置请求参数[checkLevel]未传入");
                result.put("targetRoleIds", privilegeCheckIds);
            }
            if (StringUtils.isNotBlank(privilegeCheck.getPerms())) {
                queryWrapper2.eq(UpmpPrivilegeCheck::getPerms, privilegeCheck.getPerms());
            }else {
                log.error("查询法人行权限审核配置请求参数[perms]未传入");
                result.put("targetRoleIds", privilegeCheckIds);
            }
            if(!result.containsKey("targetRoleIds")){
                List<UpmpPrivilegeCheck> privilegeChecks = baseMapper.selectList(queryWrapper2);
                privilegeChecks.forEach(item->{
                    privilegeCheckIds.add(item.getRoleId());
                });
                result.put("targetRoleIds", privilegeCheckIds);
            }

            result.put("roleDatas", roles);
        } catch (Exception e) {
            log.error("查询权限审核配置信息失败", e);
            result.put("roleData", null);
            result.put("targetRoleIds", null);
        }
        return result;
    }

    private void findCondition(LambdaQueryWrapper<UpmpPrivilegeCheck> queryWrapper, UpmpPrivilegeCheck privilegeCheck) {
        if (StringUtils.isNotBlank(privilegeCheck.getInstId())) {
            queryWrapper.eq(UpmpPrivilegeCheck::getInstId, privilegeCheck.getInstId());
        }
        if (StringUtils.isNotBlank(privilegeCheck.getChannelType())) {
            queryWrapper.eq(UpmpPrivilegeCheck::getChannelType, privilegeCheck.getChannelType());
        }
        if (StringUtils.isNotBlank(privilegeCheck.getPerms())) {
            queryWrapper.eq(UpmpPrivilegeCheck::getPerms, privilegeCheck.getPerms());
        }
        if (!ObjectUtils.isEmpty(privilegeCheck.getCheckLevel())) {
            queryWrapper.eq(UpmpPrivilegeCheck::getCheckLevel, privilegeCheck.getCheckLevel());
        }
    }

    /**
     * 根据perms获取权限审核配置信息
     *
     * @param instId
     * @param perms
     * @return
     */
    @DS("upmp")
    @Override
    public UpmpPrivilegeCheck getPrivilegeCheckByPrivilegeCode(String instId, String perms) {
        LambdaQueryWrapper wrapper = new LambdaQueryWrapper<UpmpPrivilegeCheck>()
                .eq(UpmpPrivilegeCheck::getInstId, instId)
                .eq(UpmpPrivilegeCheck::getPerms, perms);
        List<UpmpPrivilegeCheck> list = baseMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }
}
